package com.hc.appanimal;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hc.DTO.AnimalDTO;
import com.hc.DTO.AnimalImagesDTO;
import com.hc.DTO.LoginDTO;
import com.hc.DTO.SysAnimalDTO;
import com.hc.DTO.TokenDTO;
import com.hc.appanimal.LoginActivity.DownloadFileFromURL;
import com.hc.appanimal.LoginActivity.VerySlowTaskCategory;
import com.hc.constants.Constants;
import com.hc.model.utils.AnimalImagesModel;
import com.hc.model.utils.AnimalModel;
import com.hc.model.utils.SysAnimalModel;
import com.hc.model.utils.TokenModel;
import com.yyxu.download.utils.MyIntents;
import com.yyxu.download.utils.StorageUtils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AsystaskUpdateAnimal extends AsyncTask<Void, Void, Void> {
	String dateupdate = "";
	String regId;
	TokenDTO token;
	String messageerr = "";
	// LoginDTO dtoLogin;
	boolean flag = false;
	String strJson = "";
	Context mContext;
	Dialog dialog;
	AnimationDrawable frameAnimation;
	ArrayList<String> arrImgSave;
	public AsystaskUpdateAnimal(String _dateupdate, TokenDTO _token,
			Context context) {
		// dtoLogin = _dtoLogin;
		dateupdate = _dateupdate;
		arrImgSave = new ArrayList<String>();
		token = _token;
		mContext = context;
		dialog = new Dialog(mContext, R.style.NewDialog);
		dialog.setContentView(R.layout.loading);

		dialog.setCancelable(false);
		dialog.findViewById(R.id.loading_icon).setBackgroundResource(
				R.drawable.spin_animation);
		frameAnimation = (AnimationDrawable) dialog.findViewById(
				R.id.loading_icon).getBackground();
		dialog.show();
		frameAnimation.start();

	}

	@Override
	protected Void doInBackground(Void... params) {
		HttpEntity httpEntity = null;
		HttpClient client = new DefaultHttpClient();
		HttpGet method = new HttpGet(Constants.URL_ANIMAL + dateupdate);
		method.setHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=UTF-8");
		method.setHeader("Authorization",
				token.getToken_type() + " " + token.getAccess_token());
		try {
			// formEntity = new UrlEncodedFormEntity(postParams);
			// method.SET

			HttpResponse response = client.execute(method);
			httpEntity = response.getEntity();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					(response.getEntity().getContent())));
			String output;
			System.out.println("Output from Server .... \n");
			StringBuilder builder = new StringBuilder();
			while ((output = br.readLine()) != null) {
				System.out.println(output);
				builder.append(output);
			}
			
			strJson = builder.toString();
			if (strJson != null) {
				SysAnimalModel modelSys = SysAnimalModel.getInstance();
				SysAnimalDTO dtoSys = new SysAnimalDTO();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String currentDay = sdf.format(new Date());
				dtoSys.setCurrentday(currentDay);
				// dtoSys.setDateupdate(UpdatedOn);
				modelSys.updateSysAnimal(dtoSys, mContext);

				JSONArray jsonArr = new JSONArray(strJson);

				// if (jsonArr.length() > 0) {
				for (int i = 0; i < jsonArr.length(); i++) {
					JSONObject obj = jsonArr.getJSONObject(i);
					int IdAnimal = obj.getInt("Id");
					String CommonName = obj.getString("CommonName");
					String ScientificName = obj.getString("ScientificName");
					String RegionalName = obj.getString("RegionalName");
					String WLPA = obj.getString("WLPA");
					String IUCN = obj.getString("IUCN");
					String CITES = obj.getString("CITES");
					String SmallNote = obj.getString("SmallNote");
					String TradeInfo = obj.getString("TradeInfo");
					String MoreInfo = obj.getString("MoreInfo");
					String TradeMapDesc = obj.getString("TradeMapDesc");
					String TradeMapCoords = obj.getString("TradeMapCoords");
					String UpdatedOn = obj.getString("UpdatedOn");
					String ContentGuid = obj.getString("ContentGuid");
					String UserId = obj.getString("UserId");
					int AnimalCategoryId = obj.getInt("AnimalCategoryId");
					AnimalDTO animalDTO = new AnimalDTO();
					animalDTO.setId(IdAnimal);
					animalDTO.setCommonName(CommonName);
					animalDTO.setScientificName(ScientificName);
					animalDTO.setRegionalName(RegionalName);
					animalDTO.setwLPA(WLPA);
					animalDTO.setiUCN(IUCN);
					animalDTO.setcITES(CITES);
					animalDTO.setSmallNote(SmallNote);
					animalDTO.setTradeInfo(TradeInfo);
					animalDTO.setMoreInfo(MoreInfo);
					animalDTO.setTradeMapDesc(TradeMapDesc);
					animalDTO.setTradeMapCoords(TradeMapCoords);
					animalDTO.setUpdatedOn(UpdatedOn);
					animalDTO.setContentGuid(ContentGuid);
					animalDTO.setUserId(UserId);
					animalDTO.setAnimalCategoryId(AnimalCategoryId);
					// update database

					AnimalModel modelAnimal = AnimalModel.getInstance();
					boolean flag = modelAnimal.getIdAnimal(mContext, IdAnimal);
					if (!flag) {
						modelAnimal.insertAnimal(animalDTO, mContext);
					} else {
						modelAnimal.updateAnimal(animalDTO, mContext);
					}

					JSONArray arrImg = obj.getJSONArray("AnimalImages");
					for (int j = 0; j < arrImg.length(); j++) {
						JSONObject objImg = arrImg.getJSONObject(j);
						int Id = objImg.getInt("Id");
						int AnimalId = objImg.getInt("AnimalId");
						String ImageUrl = objImg.getString("ImageUrl");
						ImageUrl = ImageUrl.replaceAll(" ", "%20");
						// save images in disk
						if (ImageUrl != null) {
							arrImgSave.add(ImageUrl);
						}
						String ImageName = objImg.getString("ImageName");
						String ActualName = objImg.getString("ActualName");
						String Description = objImg.getString("Description");
						AnimalImagesDTO dto = new AnimalImagesDTO();
						dto.setId(Id);
						dto.setAnimalId(AnimalId);
				
						dto.setImageUrl(ImageUrl);
						dto.setImageName(ImageName);
						dto.setActualName(ActualName);
						dto.setDescription(Description);
						AnimalImagesModel modelImg = AnimalImagesModel
								.getInstance();
						boolean checkImg = modelImg.getIdImges(mContext, Id);
						if (!checkImg) {
							modelImg.insertImages(dto, mContext);
						} else {
							modelImg.updateImamges(dto, mContext);
						}

						// arrData.add(dto);

					}

				}
				// } else {
				// JSONObject jsonerr = new JSONObject(strJson);
				// messageerr = jsonerr.getString("Message");
				// }

			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			flag = true;
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		for (String path : arrImgSave) {
			String[] strs = path.split("/");
			File f = new File(Environment.getExternalStorageDirectory()
					+ "/" + Constants.APP_NAME + "/" + strs[4] + "/"
					+ strs[5]);
			if (!f.exists()) {
				Intent downloadIntent = new Intent("com.yyxu.download.services.IDownloadService");
                downloadIntent.putExtra(MyIntents.TYPE, MyIntents.Types.ADD);
                downloadIntent.putExtra(MyIntents.URL, path);
                mContext.startService(downloadIntent);
			}
		}
		dialog.dismiss();
		frameAnimation.stop();
		
		if (flag) {
			Intent intent = new Intent(mContext, LoginActivity.class);
			mContext.startActivity(intent);
		} else {
			if (arrImgSave.size() > 0) {
//				flagDialog = false;
				new DownloadFileFromURL(arrImgSave, token).execute();
			}else{
				new AsystaskUpdateCategory(mContext, token).execute();
			}
			
		}

	}
	
	class DownloadFileFromURL extends AsyncTask<Void, String, String> {
		Dialog dialog4;
		AnimationDrawable frameAnimation4;
		// String urlDowload = "";
		ArrayList<String> arrImgSave;
		TokenDTO token;

		public DownloadFileFromURL(ArrayList<String> arrDowload, TokenDTO _token) {

			arrImgSave = arrDowload;
			token = _token;
			dialog4 = new Dialog(mContext, R.style.NewDialog);
			dialog4.setContentView(R.layout.loading);

			dialog4.setCancelable(false);

			dialog4.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation4 = (AnimationDrawable) dialog4.findViewById(
					R.id.loading_icon).getBackground();
			TextView localTextView = (TextView) dialog4.findViewById(16908310);
			localTextView.setText("Downloading data\n Please wait");
			localTextView.setTextSize(25.0F);
			localTextView.setGravity(Gravity.CENTER_VERTICAL
					| Gravity.CENTER_HORIZONTAL);
			dialog4.show();
			frameAnimation4.start();
		}

		@Override
		protected String doInBackground(Void... param) {
			int count;
			try {
				ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo netInfo = cm.getActiveNetworkInfo();

				if (netInfo != null && netInfo.isConnected()) {
					for (String urlDowload : arrImgSave) {
						String[] strsFile = urlDowload.split("/");
						File f = new File(
								Environment.getExternalStorageDirectory() + "/"
										+ Constants.APP_NAME + "/"
										+ strsFile[4] + "/" + strsFile[5]);
						if (!f.exists()) {
							URL url = new URL(urlDowload);

							HttpURLConnection conection = (HttpURLConnection) url
									.openConnection();

							conection.setRequestProperty("Connection", "close");
							conection.setConnectTimeout(2000); // Timeout 2
																// seconds.
							conection.connect();

							if (conection.getResponseCode() == 200) // Successful
																	// response.
							{
								// getting file length
								// input stream to read file - with 8k buffer
								InputStream input = new BufferedInputStream(
										url.openStream(), 8192);
								String[] strs = urlDowload.split("/");
								// Output stream to write file
								OutputStream output = new FileOutputStream(
										new File(StorageUtils.FILE_ROOT,
												strs[5]));

								byte data[] = new byte[1024];

								long total = 0;

								while ((count = input.read(data)) != -1) {
									total += count;
									// writing data to file
									output.write(data, 0, count);
//									size--;
								}

								// flushing output
								output.flush();

								// closing streams
								output.close();
								input.close();

							} else {
								//
							}
						}

					}

				} else {
				}

			} catch (Exception e) {
				Log.e("Error: ", e.getMessage());
			}

			return null;
		}

		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			dialog4.dismiss();
			frameAnimation4.stop();
			new AsystaskUpdateCategory(mContext, token).execute();
		}

	}

}
